/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.fieldscope.api;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Represents a single value in a schema.
 * 
 * @author Travis Keep
 */
public class Value {
  
  private final String label;
  private final Object value;
  
  /**
   * The label. This is what is displayed to user in combo box.
   */
  public String getLabel() {
    return label;
  }

  /**
   * The value. This is passed as value to the map argument of.
   * {@link FieldscopeApi#addObservation(String, long, long, java.util.Map)}
   */
  public Object getValue() {
    return value;
  }
  
  @Override
  public String toString() {
    return String.format("{label=%s, value=%s}", label, value);
  }
  
  static List<Value> fromJSON(JSONArray json, ValueType valueType) throws JSONException {
    List<Value> result = new ArrayList<Value>(json.length());
    for (int i = 0; i < json.length(); i++) {
      result.add(singleFromJSON(json.getJSONObject(i), valueType));
    }
    return result;
  }
  
  private Value(String label, Object value) {
    this.label = label;
    this.value = value;
  }

  private static Value singleFromJSON(JSONObject jsonObject, ValueType valueType) throws JSONException {
    String label = jsonObject.getString("label");
    Object value;
    switch (valueType) {
      case NUMERIC:
        value = jsonObject.getDouble("value");
        break;
      case STRING:
        value = jsonObject.getString("value");
        break;
      default:
        throw new JSONException("Got unexpected value type: " + valueType);
    }
    return new Value(label, value);
  }
}
